package utils

import (
	"encoding/json"
	"fmt"
	alimt20181012 "github.com/alibabacloud-go/alimt-20181012/v2/client"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/gogf/gf/frame/g"
)

//{
//"RequestId": "476F0D14-90C6-5EF4-8ECA-B76CB55859CB",
//"Data": {
//"WordCount": "93",
//"Translated": "航空沥青，沥青_户外_地板_道路_人made_aerial，道路_平面_破裂，航空_沥青t_01"
//},
//"Code": "200"
//}

type TranslateResponse struct {
	RequestId string `json:"RequestId"`
	Data      struct {
		WordCount  string `json:"WordCount"`
		Translated string `json:"Translated"`
	}
	Code string `json:"Code"`
}

/**
 * 使用AK&SK初始化账号Client
 * @param accessKeyId
 * @param accessKeySecret
 * @return Client
 * @throws Exception
 */
func CreateClient() (_result *alimt20181012.Client, _err error) {
	// 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378661.html。
	config := &openapi.Config{
		// 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
		AccessKeyId: tea.String(g.Cfg().GetString("aliyun_translate.access_key_id")),
		// 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
		AccessKeySecret: tea.String(g.Cfg().GetString("aliyun_translate.access_key_secret")),
	}
	// Endpoint 请参考 https://api.aliyun.com/product/alimt
	config.Endpoint = tea.String("mt.cn-hangzhou.aliyuncs.com")
	_result = &alimt20181012.Client{}
	_result, _err = alimt20181012.NewClient(config)
	return _result, _err
}

/**
 * API 相关
 * @param path params
 * @return OpenApi.Params
 */
func CreateApiInfo() (_result *openapi.Params) {
	params := &openapi.Params{
		// 接口名称
		Action: tea.String("TranslateGeneral"),
		// 接口版本
		Version: tea.String("2018-10-12"),
		// 接口协议
		Protocol: tea.String("HTTPS"),
		// 接口 HTTP 方法
		Method:   tea.String("POST"),
		AuthType: tea.String("AK"),
		Style:    tea.String("RPC"),
		// 接口 PATH
		Pathname: tea.String("/"),
		// 接口请求体内容格式
		ReqBodyType: tea.String("formData"),
		// 接口响应体内容格式
		BodyType: tea.String("json"),
	}
	_result = params
	return _result
}

func TranslateToENOne(text string) (string, error) {
	client, _err := CreateClient()
	if _err != nil {
		return "", _err
	}

	params := CreateApiInfo()
	// body params
	body := map[string]interface{}{}
	body["FormatType"] = tea.String("text")
	body["SourceLanguage"] = tea.String("zh")
	body["TargetLanguage"] = tea.String("en")
	body["SourceText"] = tea.String(text)
	body["Scene"] = tea.String("general")
	// runtime options
	runtime := &util.RuntimeOptions{}
	request := &openapi.OpenApiRequest{
		Body: body,
	}
	// 复制代码运行请自行打印 API 的返回值
	// 返回值为 Map 类型，可从 Map 中获得三类数据：响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
	result, _err := client.CallApi(params, request, runtime)
	if _err != nil {
		return "", _err
	}
	var response TranslateResponse

	resultJson, err := json.Marshal(result["body"])
	if err != nil {
		fmt.Println("Error:", err.Error())
	}
	err = json.Unmarshal([]byte(resultJson), &response)
	if err != nil {
		fmt.Println("Error:", err.Error())
	}
	Translated := response.Data.Translated

	Translated = "idp texture of " + Translated
	return Translated, nil
}

func TranslateToEN(args []string) ([]string, error) {
	client, _err := CreateClient()
	if _err != nil {
		return nil, _err
	}

	var translateList []string
	for _, val := range args {
		params := CreateApiInfo()
		// body params
		body := map[string]interface{}{}
		body["FormatType"] = tea.String("text")
		body["SourceLanguage"] = tea.String("zh")
		body["TargetLanguage"] = tea.String("en")
		body["SourceText"] = tea.String(val)
		body["Scene"] = tea.String("general")
		// runtime options
		runtime := &util.RuntimeOptions{}
		request := &openapi.OpenApiRequest{
			Body: body,
		}
		// 复制代码运行请自行打印 API 的返回值
		// 返回值为 Map 类型，可从 Map 中获得三类数据：响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
		result, _err := client.CallApi(params, request, runtime)
		if _err != nil {
			return nil, _err
		}
		var response TranslateResponse

		resultJson, err := json.Marshal(result["body"])
		if err != nil {
			fmt.Println("Error:", err.Error())
			// handle error
		}

		err = json.Unmarshal([]byte(resultJson), &response)
		if err != nil {
			fmt.Println("Error:", err.Error())
		}
		Translated := response.Data.Translated
		translateList = append(translateList, Translated)
	}

	return translateList, nil
}
